#!/usr/bin/python
# -*- coding:utf-8 -*-
# @time: 2021/5/17 5:32 下午

from collections import OrderedDict
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination


class CustomPagination(PageNumberPagination):
    page_size = 10
    page_query_param = 'page'
    page_size_query_param = 'pageSize'
    max_page_size = 100

    def get_paginated_response(self, data):
        result = {
            "status": "success",
            "errcode": 0,
            "data": OrderedDict(
                [
                    ('count', self.page.paginator.count),
                    ('next', self.get_next_link()),
                    ('previous', self.get_previous_link()),
                    ('data', data),
                ]
            ),
        }
        return Response(result)


def pagination(result, page=None, page_size=None):
    """定义了一个非ORM手动分页器， 可在需要的视图中使用"""
    if not page:
        page = 1
    if not page_size:
        page_size = 10
    total = len(result)
    total_page = (total - 1) // page_size + 1
    if page > total_page:
        page = 1
    start = (page - 1) * page_size
    result = {
        'total': total,
        'page': page,
        'total_page': total_page,
        'page_size': page_size,
        'data': result[start : start + page_size],
    }
    return result
